import React, { memo, useEffect, useRef, useState } from "react";
import {
  getTodo,
  addTodo,
  delTodo,
  getItem,
  WriteTodo,
  getList,
} from "../api/todo";
import {
  Space,
  Table,
  Drawer,
  Button,
  Form,
  Input,
  Col,
  Row,
  Select,
  Popconfirm,
  message
} from "antd";
import AgeRange from "../components/AgeRange";
const Todo3 = memo(() => {
  //form表单的实例
  const [basic] = Form.useForm();
  const [searchForm] = Form.useForm();
  //存放数据的数组
  const [list, setList] = useState([]);
  //控制抽屉的变量
  const [open, setOpen] = useState(false);
  //存放点击学生的ID
  const currentID = useRef("");
  //增加学生信息是用户输入的数据
  let students = {};
  let initValue = { name: "", sex: "", age: "", score: "" };
  //初始化数据函数
  let initList = async () => {
    let res = await getTodo();
    setList(res.data);
  };
  //数据回显的函数
  let lookItem = async (id) => {
    let res = await getItem(id);
    //设置ID值
    currentID.current = id;
    //先让抽屉出现才能获取form实例
    setOpen(true);
    basic.setFieldsValue(res.data);
  };
  //点击搜索按钮时的回调
  let onSearch = async (values) => {
    /*
      age: undefined
      name_like: undefined
      sex: 所有
    */
    // undefined值，如果强制转成字符串，会被转成字符串'undefined'
    //拷贝values去data ，去掉undefined
    const data = {};
    for (let k in values) {
      //如果values[k] 不是undefined
      if (values[k]) {
        data[k] = values[k];
      }
    }
    if (data.age) {
      //如果data.Age存在 证明用户输入了内容
      // 按照年龄范围搜索的处理
      data["age_gte"] = data.age[0];
      data["age_lte"] = data.age[1];
      //删除掉age
      delete data.age;
    }
    console.log("当前搜索条件：", data);
    const res = await getList(data);
    setList(res.data);
  };

  //组件加载完毕请求数据
  useEffect(() => {
    initList();
  }, []);
  //表头数据
  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "年龄",
      dataIndex: "age",
      key: "age",
    },
    {
      title: "性别",
      dataIndex: "sex",
      key: "sex",
    },
    {
      title: "成绩",
      dataIndex: "score",
      key: "score",
    },
    {
      title: "时间",
      dataIndex: "time",
      key: "time",
    },
    {
      title: "操作",
      key: "action",
      render: (_, item) => (
        <Space size="middle">
          <span
            onClick={() => {
              lookItem(item.id);
            }}
          >
            修改
          </span>
          <Popconfirm
            title="删除功能"
            description="你确定要删除吗?"
            onConfirm={async () => {delTodo(item.id);initList();message.success('删除成功');}}
            onCancel={()=>{message.error('取消删除')}}
            okText="是"
            cancelText="否"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  return (
    <div>
      <Form
        form={searchForm}
        name="searchForm"
        onFinish={onSearch}
        initialValues={{ sex: "" }}
      >
        <Row gutter={24}>
          <Col span={8}>
            <Form.Item label="姓名" name="name_like">
              <Input />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="性别" name="sex">
              <Select
                options={[
                  { value: "男", label: "男" },
                  { value: "女", label: "女" },
                  { value: "", label: "所有" },
                ]}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="年龄范围" name="age">
              <AgeRange></AgeRange>
            </Form.Item>
          </Col>
        </Row>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button onClick={(e) => searchForm.resetFields()}>重置</Button>
          </Space>
        </Form.Item>
      </Form>
      <Table dataSource={list} columns={columns} />;
      <div>
        <Button
          type="primary"
          onClick={() => {
            setOpen(true);
          }}
        >
          添加学生
        </Button>
      </div>
      <Drawer
        title="添加学生"
        placement="bottom"
        closable={false}
        onClose={() => {
          setOpen(false);
        }}
        open={open}
      >
        <Form
          name="basic"
          form={basic}
          //表单中的输入框的默认值
          initialValues={initValue}
          //输入框输入内容时的事件；两个参数：第一个是每个输入框的值，第二个是所有输入框值的对象
          onValuesChange={(v, all) => {
            // 给学生信息对象赋值
            students = all;
          }}
        >
          <Form.Item
            label="学生姓名"
            name="name"
            rules={[
              {
                required: true,
                message: "请输入学生姓名!",
              },
            ]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="学生年纪"
            name="age"
            rules={[
              {
                required: true,
                message: "请输入学生年纪!",
              },
            ]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="学生性别"
            name="sex"
            rules={[
              {
                required: true,
                message: "请输入学生性别!",
              },
            ]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="学生成绩"
            name="score"
            rules={[
              {
                required: true,
                message: "请输入学生成绩!",
              },
            ]}
          >
            <Input></Input>
          </Form.Item>
        </Form>
        <Form.Item>
          <Space>
            <Button
              type="primary"
              htmlType="submit"
              onClick={async () => {
                if (currentID.current === "") {
                  await addTodo({
                    id: new Date().getTime(),
                    key: new Date().getTime(),
                    time:
                      new Date().toLocaleDateString() +
                      "-" +
                      new Date().toLocaleTimeString(),
                    ...students,
                  });

                  initList();
                  currentID.current = "";
                  setOpen(false);
                } else {
                  WriteTodo(currentID.current, { ...students });
                  initList();
                  basic.setFieldsValue({
                    name: "",
                    sex: "",
                    age: "",
                    score: "",
                  });
                  currentID.current = "";
                  setOpen(false);
                }
              }}
            >
              确定
            </Button>
            <Button
              type="primary"
              danger
              onClick={() => {
                setOpen(false);
              }}
            >
              取消
            </Button>
          </Space>
        </Form.Item>
      </Drawer>
    </div>
  );
});

export default Todo3;
